<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜素与添加区 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select
            v-model="queryInfo.sex"
            clearable
            @clear="getUserListToFirstPage"
            placeholder="请选择"
          >
            <el-option
              v-for="item in __SEX_OPTIONS__"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入内容"
            clearable
            @clear="getUserListToFirstPage"
          >
            <el-button
              @click="getUserListToFirstPage"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialog"> 添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table v-loading="loading" :data="userlist" border stripe>
        <el-table-column
          label="#"
          type="index"
          :index="index1"
        ></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
          :cell-click="handleDetailClick"
        >
          <template v-slot="scope">
            <span class="clickable" @click="handleDetailClick(scope.row.id)">{{
              scope.row.username
            }}</span>
          </template></el-table-column
        >
        <el-table-column label="性别" prop="mg_sex">
          <template slot-scope="scope">
            {{
              __getLabelByValue__(scope.row.mg_sex, __SEX_OPTIONS__, '默认无')
            }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="onChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
              ></el-tooltip
            >
            <!-- 删除 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delOpen(scope.row.id)"
              ></el-button>
              ></el-tooltip
            >
            <!-- 分配角色 -->
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button
            ></el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :disabled="loading"
      >
      </el-pagination>
    </el-card>

    <!-- 分配角色对话框 -->
    <el-dialog
      @close="setRoleDialogClosed"
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
    >
      <div>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>
          分配新角色：

          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹窗 -->
    <userDialogs
      :open="open"
      :type="type"
      :current="current"
      @handleClose="handleClose"
      @handleOk="handleOk"
    />
  </div>
</template>

<script>
// var a = 'query=&pagenum=的&pagesize=2'
// var b = a.split('&')
// var c = {}
// b.forEach((n) => {
//   var [key, value] = n.split('=')
//   // var key = d[0]
//   // var value = d[1]

//   c[key] = value
//   // c[d[0]] = d[1]
// })
import userDialogs from './UserDialogs.vue'
export default {
  components: {
    userDialogs,
  },
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (!regEmail.test(value)) {
        callback(new Error('请输入合法的邮箱'))
      }
      callback()
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (!regMobile.test(value)) {
        callback(new Error('请输入合法的电话'))
      }
      callback()
    }
    return {
      // 当前操作的对象
      current: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        sex: 0,
      },
      // 当前操作的类型
      type: 1,
      // 弹窗是否显示
      open: false,
      // 角色下拉框默认id
      selectRoleId: '',
      // 角色列表
      roleList: [],
      // 获取用户列表的参数对象
      queryInfo: {
        sex: undefined,
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示的数量
        pagesize: 4,
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      userlist: [],
      // 总条目数
      total: 0,

      loading: true,
    }
  },
  created() {
    this.getUserList()
  },

  methods: {
    // 监听开关状态的改变
    async onChange(userinfo) {
      // console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 获取用户列表
    async getUserList() {
      this.loading = true
      const { data: res } = await this.$http
        .get('users', {
          params: this.queryInfo,
        })
        .then((result) => {
          // 成功的回调
          // console.log('成功的回调')
          return result
        })
        .catch(() => {
          // 失败的回调
          // console.log('失败的回调')
          return Promise.reject('抛出错误')
        })
        .finally(() => {
          // console.log('成功或失败都会执行的回调')
          this.loading = false
        })

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      // console.log(res)
      this.userlist = res.data.users
      this.total = res.data.total
    },
    getUserListToFirstPage() {
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newpage) {
      // console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 查看
    async handleDetailClick(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 查询成功，将用户数据保存到editForm 中
      this.current = {
        ...res.data,
        sex: res.data.mg_sex,
      }
      this.open = true
      this.type = 1
    },
    // 关闭弹窗
    handleClose() {
      this.open = false
      this.type = 1
      this.current = {}
    },
    addDialog() {
      this.current = {}
      this.type = 3
      this.open = true
    },

    // 点击 确认 按钮
    async handleOk() {
      // 编辑
      if (this.type === 2) {
        const { data: res } = await this.$http.put('users/' + this.current.id, {
          email: this.current.email,
          mobile: this.current.mobile,
          sex: this.current.sex,
        })
        // console.log(res)
        if (res.meta.status !== 200)
          return this.$message.error('更新用户信息失败')

        this.$message.success('更新用户信息成功')
        // 新增
      } else if (this.type === 3) {
        const { data: res } = await this.$http.post('users', this.current)
        if (res.meta.status != 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // console.log(res)
      }
      this.open = false
      this.type = 1
      this.current = {}
      this.getUserList()
    },
    // 编辑
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 查询成功，将用户数据保存到editForm 中
      this.current = {
        ...res.data,
        sex: res.data.mg_sex,
      }
      this.type = 2
      // 显示弹框
      this.open = true
    },

    // // 修改用户信息
    // eidtUser() {
    //   // 首先验证表单合法
    //   this.$refs.editFormRef.validate(async (valide) => {
    //     if (!valide) {
    //       return this.$message.error('请填写完整用户信息')
    //     }
    //     const { data: res } = await this.$http.put(
    //       'users/' + this.editForm.id,
    //       {
    //         email: this.editForm.email,
    //         mobile: this.editForm.mobile,
    //         sex: this.editForm.sex,
    //       }
    //     )
    //     // console.log(res)
    //     if (res.meta.status !== 200)
    //       return this.$message.error('更新用户信息失败')
    //     // 关闭弹框
    //     this.editDialogVisible = false
    //     // 重新请求最新数据
    //     this.getUserList()
    //     this.$message.success('更新用户信息成功')
    //   })
    // },
    // 根据id删除对应的用户信息
    async delOpen(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(confirmResult)
      // 点击取消删除
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 确认删除
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('不允许删除admin账户')
      }
      this.getUserList()
      this.$message.success('删除成功')
    },
    // 展示分配角色对话框
    async setRole(userInfo) {
      // 获取用户信息
      this.userInfo = userInfo
      // 获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 点击按钮，分配角色
    async saveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      // const { data: res } = await this.$http.put(
      //   'users/${this.userInfo.id}/role',
      //   { rid: this.selectRoleId }
      // )
      // if (res.meta.status != 200) return this.$message.error('更新角色失败！')

      // this.$message.error('更新角色成功！')
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.selectRoleId }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 关闭分配权限对话框触发
    setRoleDialogClosed() {
      // 重置下拉框的内容
      this.selectRoleId = ''
      this.userInfo = {}
    },
    index1(index) {
      if (this.queryInfo.pagenum === 1) {
        return index + 1
      }
      if (this.queryInfo.pagenum != 1) {
        return (
          (index += (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize) + 1
        )
      }
    },
  },
}
</script>

<style scoped>
.clickable {
  cursor: pointer; /* 设置鼠标指针为手形 */
}

.clickable:hover {
  text-decoration: underline; /* 鼠标悬停时文字下划线 */
}
</style>
